package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;


import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author Marco
 * @Description
 * @date 2025/8/4 20:47
 * @email 3293336923@qq.com
 */
public class JwtUtil {


    //  秘钥
    private static SecretKey secretKey = Keys.hmacShaKeyFor("hG3lV7oA2oG2rU2tP0mM7vS4hB3mJ1iS".getBytes());

    /**
     * 生成  token
     *
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(Long userId, String username) {

        String jwt = Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + 3600000))
                .setSubject("LOGIN_USER")
                .claim("userId", userId)
                .claim("username", username)
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();

        return jwt;
    }

    /***
     *  解析 token
     * @param token
     */

    public static Claims parseToken(String token) {

        if (token == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder()
                    .setSigningKey(secretKey)
                    .build();
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
//            返回 payload 实体
           return  claimsJws.getBody();
        } catch (ExpiredJwtException e) {
//            json  过期
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
//            json  非法
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    public static void main(String[] args) {


//        在 当前的 方法中，可以 生成生成一个 很长时间的 token，便于测试
        String jwt = createToken(8L, "13469568763");
        System.out.println("jwt = " + jwt);

    }
}
